# coding: utf-8
import random
import calendar as cal
import datetime

from django.db import transaction

import users.countries
from users.models import Profile
from cart.models import Order, StorageItem
from goods.models import Product

USERNAME_FORMAT = 'test__%d'
COUNTRIES_COUNT = 20
COUNTRIES = users.countries.COUNTRIES[:COUNTRIES_COUNT]
COOL_CITIES = ['Лондон', 'Санкт-Петербург', 'Копенгаген', 'Бомбей', 'Сидней', 'Лиссабон', 'Амстердам',] #(c) OS Larkina

random_item = lambda l: l[random.randint(0, len(l) - 1)]

@transaction.commit_on_success
def fill_users():
	with open('db/names.txt', 'r') as f:
		ns = [n.strip() for n in f.readlines()]

	ps = []
	for i in range(1, 250):
		ps.append(Profile.objects.create(
			username=USERNAME_FORMAT % i,
			first_name=random_item(ns),
			country=random_item(COUNTRIES)[0],
		))
	return ps

@transaction.commit_on_success
def fill_orders(ps):
	y = 2011
	for p in ps:
		print "%s to the rescue! (%s)" % (p.first_name, p.username)
		for m in range(1, 13): #each month user is bought
			for i in range(0, 3): #3 films
				d = random.randint(1, cal.monthrange(y, m)[1]) #in random day
				date = datetime.datetime(y, m, d) #at 0:00 =P

				products = []
				while not products:
					#choose some from top-250 generated by filldb.py
					products = Product.objects.filter(pk=random.randint(1, 250))

				o = Order.objects.create(
					assignee=p,
					payment=products[0].cost,
					address="ololo i'm livin' there",
					country=p.country,
					city=random_item(COOL_CITIES),
					date=date
				)
				o.date = date #with fuckin' respect to auto_now_add
				o.save()
				StorageItem.objects.create(
					storage=o,
					product=products[0],
					count=1
				)


try:
	Profile.objects.get(username=USERNAME_FORMAT % 1)
except Profile.DoesNotExist:
	ps = fill_users()
	fill_orders(ps)
	print "SUCCESS"
else:
	print "Users already exist. Do your stuff manually."
	def fill_manually_fast():
		fill_orders(Profile.objects.filter(username__startswith="test__"))
